package org.platform.lwc.gateway.filter;

import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.gateway.config.LoadBalancerProperties;
import org.springframework.cloud.gateway.filter.LoadBalancerClientFilter;
import org.springframework.web.server.ServerWebExchange;

import java.util.Map;

public class SocketioLoadBalancerClientFilter extends LoadBalancerClientFilter {

    public SocketioLoadBalancerClientFilter(LoadBalancerClient loadBalancer, LoadBalancerProperties properties) {
        super(loadBalancer, properties);
    }


    /**
     * 实现转发到socketio集群，但是集群内socketio服务端口必须固定
     */
    protected ServiceInstance choose(ServerWebExchange exchange) {
        ServiceInstance serviceInstance = super.choose(exchange);
        if(null != serviceInstance && "netty-service".equals(serviceInstance.getServiceId())
                && exchange.getRequest().getPath().toString().contains("/socket.io/")) {
            return new DefaultServiceInstance(serviceInstance.getInstanceId(), serviceInstance.getServiceId(),
                    serviceInstance.getHost(), 9090, serviceInstance.isSecure());
        }
        return serviceInstance;
    }
}